//
//  HMComposeView.swift
//  WeiBo
//
//  Created by 李立达 on 15/12/14.
//  Copyright © 2015年 heima11. All rights reserved.

import UIKit
import pop

class HMComposeView: UIView {
    
   private lazy var coverView : UIImageView = {
        //懒加载背景模糊图片
    let view = UIImageView(image: UIImage.getInterceptScreen().applyLightEffect())
        return view
    }()
    
    
    var target : UIViewController?
    //懒加载宣传图片
  private  lazy var sloganImageView : UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
   private lazy var buttons : [HMComPoseButton] = [HMComPoseButton]()
    
     override init(frame: CGRect) {
        
        super.init(frame: frame)
        self.width = SCREENW
        self.height = SCREENH
        setupUI()
           }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //手势退出页面方法
    func exitCompose(){
        
        for (i,value) in buttons.enumerate()
        {
            animStart(value, isup: false, index: i)
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            
            self.removeFromSuperview()
            
        })
   
    }
    
    //初始化视图方法
    func setupUI() {
        backgroundColor=randColor()
        let top = UITapGestureRecognizer()
        addGestureRecognizer(top)
        top.numberOfTapsRequired = 1
        top.numberOfTouchesRequired = 1
        
        top.addTarget(self, action: "exitCompose")
        addSubview(coverView)
        addSubview(sloganImageView)
        coverView.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(self)
            make.size.equalTo(self)
        }
        
        sloganImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self.snp_top).offset(100)
        }
        
        addChildButton()
    }
    

    //MARK : 添加button方法
       func addChildButton(){
        
            let childW = CGFloat(80)
            let childH = CGFloat(110)
            let butttonmessage = self.getButtomMessage()
            //MARK : 根据数据模型添加button
            for (i,value) in butttonmessage.enumerate()
            {
                let icon = value.icon
                let title = value.title
                
                let maigc:CGFloat = (SCREENW - 3 * childW) / 4
                
                let col = i % 3
                let row = i / 3
                
            let button = HMComPoseButton()
                
            button.setTitle(title, forState: .Normal)
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = i
            button.setImage(UIImage(named: icon!), forState:.Normal)
                
            button.x = childW * CGFloat(col) + (CGFloat(col)+1)*maigc
                
            button.y = CGFloat(row) * (maigc + childH) + SCREENH
                
            button.size = CGSize(width: childW, height: childH)
            addSubview(button)
                
            buttons.append(button)
            }
       }
    
   @objc func buttonClick(button:UIButton){
    
//    MARK : button点击方法执行动画 跳转 控制器
       UIView.animateWithDuration(0.25,
            animations: { () -> Void in
            button.transform = CGAffineTransformMakeScale(1.5, 1.5)
            }) { (_) -> Void in
                
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
            button.transform = CGAffineTransformIdentity
                
            }, completion: { (_) -> Void in
                    
             let composeVc = HMComPoseViewController()
                
             self.target?.presentViewController(
                   HMNavigationViewController(rootViewController:composeVc),
                   animated: true,
                   completion: { () -> Void in
                    
                   self.removeFromSuperview()
                    
                   })
                })
            }
//    UIView.animateWithDuration(0.25, animations: { () -> Void in
//        for value in self.buttons {
//            value.alpha = 0.2
//            if value == button {
//                // 是当前的按钮,
//                // 执行放大透明
//                value.transform = CGAffineTransformMakeScale(2, 2)
//            }else{
//                // 执行缩小透明
//                value.transform = CGAffineTransformMakeScale(0.3, 0.3)
//            }
//        }
//        }) { (_) -> Void in
//            let composeVC = HMComPoseViewController()
//            // 弹
//            self.target?.presentViewController(HMNavigationViewController(rootViewController: composeVC), animated: true, completion: { () -> Void in
//                self.removeFromSuperview()
//            })
//    }
    }
    
    
   //执行动画的方法
    func animStart(button:UIButton,isup:Bool,index: Int){
    
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        
        let y:CGFloat = isup ? button.center.y - (300 * autosize) : button.center.y + (300 * autosize)
        
        anim.toValue = NSValue(CGPoint: CGPointMake(button.center.x, y))
        
        anim.springBounciness = 8
        
        anim.springSpeed = 10
        
        anim.beginTime = CACurrentMediaTime()+Double(index) * 0.025
        
        button.pop_addAnimation(anim, forKey: nil)
    }
    
    //MARK : 读取button的plist以及转换model
    func getButtomMessage() ->[HMComposeModel]{
    
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        
        let combuttons = NSArray(contentsOfFile: path!)
        
        var result = [HMComposeModel]()
        
        for value in combuttons!
        {
            result.append(HMComposeModel(dict: value as! [String : AnyObject]))
        }
        return result
    }
    
    
    func show(target:UIViewController) {
        
        self.target = target;
         target.view?.addSubview(self)
        
        for (i,value) in buttons.enumerate()
        {
            animStart(value, isup: true, index: i)
        }
    }
}
